
// import { getToken } from '@/utils/auth'
import userState from '@/store/modules/user'
// webscokets 的参数集
const state = {
  // 用户令牌
  userToken: 'TEST0001DZIK2020TEST0001',
  // 用户编码
  userCode: userState.state.userCode,
  // 客户端编码
  clientCode: '',
  // 客户端类型
  clientType: 'PcFrame',
  // 客户端消息序列号
  clientSerial: userState.state.userCode + (new Date()).getTime(),
  // 消息类型
  // type: '',
  // 签名
  sign: '1',
  // 时间戳
  timeStamp: (new Date()).getTime(),
  // 请求数据
  data: {
    // 用户编码
    userCode: ''
  },
  // 连接时间
  relinkInterval: '',
  // 连接时间值
  relinkIntervalNumber: 10 * 1000,
  // 用户组列表
  userGroupList: '',
  // 用户列表
  userList: '',
  // 在线用户列表
  onLineuserGroupList: '',
  // 用户收到来自其他用户的消息
  messageGroupList: {},
  // // 用户消息
  // messageGroupList: '',

  // 未读消息清单
  responseMessageList: '',
  // 用户发送成功的消息 发送消息清单
  requestMessageList: '',
  // 当前用户
  currentUser: '',

  // 建立连接需要的参数
  host: 'http://192.168.1.160:12088/imserver/',
  socket: null, // websocoket
  lockReturn: false, // 是否真正建立连接
  timeout: 10 * 1000, // 10秒一次心跳
  timeoutObj: null, // 心跳倒计时
  serverTimeoutObj: null, // 服务器心跳倒计时
  reloadInterval: null // 断开 重连倒计时 刷新时间
}
const mutations = {
  setWsUrl(state, val) {
    state.host = val
  },
  setSocket(state, val) {
    state.socket = val
  },
  setUserToken(state, val) {
    state.userToken = val
  },
  setTimeoutNum(state, val) {
    state.timeoutNum = val
  },
  setTimeoutObj(state, val) {
    state.timeoutObj = val
  },
  // websockets中的值
  setWsMsg(state, requestMessageList) {
    state.requestMessageList = requestMessageList
  },
  // 添加来自其他用户的消息
  setWsUserMsg(state, msg) {
    const data = JSON.parse(JSON.stringify(state.messageGroupList))
    if (Object.keys(data).includes(msg.from)) {
      data[msg.from].push(msg)
    } else {
      data[msg.from] = []
      data[msg.from].push(msg)
    }
    state.messageGroupList = data
  },
  // 用户的token
  userToken(state, userToken) {
    state.userToken = userToken
  },
  // 用户编码
  userCode(state, userCode) {
    state.userCode = userCode
  },
  // 客户端编码
  clientCode(state, clientCode) {
    state.clientCode = clientCode
  },
  // 客户端消息序列号
  serial(state, serial) {
    state.serial = serial
  },
  // 签名
  sign(state, sign) {
    state.sign = sign
  },

  // data中的数据（以下）
  // userCode
  dataFrom(state, from) {
    state.data.from = from
  },
  // datapassWord
  dataToType(state, toType) {
    state.data.toType = toType
  },
  // dataFromType
  dataFromType(state, FromType) {
    state.data.fromType = FromType
  },
  // dataFromUserCode
  datafromUserCode(state, fromUserCode) {
    state.data.fromUserCode = fromUserCode
  },
  // dataTo
  dataTo(state, to) {
    state.data.to = to
  },
  // datatitle
  datatitle(state, title) {
    state.data.title = title
  },
  // datacontext
  datacontext(state, context) {
    state.data.context = context
  }
}
const actions = {
  // 初始化webSocket长连接
  initWebSocket({ state, commit, dispatch }) {
    if (typeof WebSocket === 'undefined') {
      console.log('您的浏览器不支持WebSocket')
    } else {
      console.log('您的浏览器支持WebSocket')
      // 实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
      // 等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
      const host = (state.host + state.userToken).replace('https', 'wss').replace('http', 'ws')
      // commit('setWsUrl', host)
      if (state.socket != null) {
        dispatch('close')
        commit('setSocket', null)
        commit('setUserToken', '')
      }
      const soc = new WebSocket(host)
      soc.onopen = function() {
        // 开始websocket心跳
        dispatch('startWsHeartbeat')
      }
      soc.onclose = function(e) {
        console.log(e, 'ws 关闭')
      }
      soc.onmessage = function(e) {
        const receive = JSON.parse(e.data)
        console.log(receive, '收到服务器信息receive', receive.context)
        // 其他用户信息
        if (receive.type === 'userMessage') {
          commit('setWsUserMsg', receive)
        }
        // 服务端发送来的消息存到vuex
        if (receive.type === 'getMessage') {
          commit('setWsMsg', receive.context)
        }

        // 每次接收到服务端消息后 重置websocket心跳
        dispatch('resetHeartbeat')
      }
      soc.onerror = function(err) {
        console.log(err, 'ws 错误')
        // state.userToken = ''
        dispatch('setUserToken', '')
        dispatch('reconnect')
      }
      commit('setSocket', soc)
    }
  },
  // 重新连接重启websocket
  reconnect({ state, commit, dispatch }) {
    // if (_this.lockReturn) {
    //   return;
    // }

    // _this.lockReturn = true;
    // 没连接上会一直重连，设置延迟避免请求过多
    state.timeoutNum && clearTimeout(state.timeoutNum)
    // state.timeoutNum = setTimeout(function() {
    //   // 新连接
    //   dispatch('initWebSocket')
    //   // _this.lockReturn = false;
    // }, 3000)
    commit('setTimeoutNum', setTimeout(function() {
      // 新连接
      dispatch('initWebSocket')
      // _this.lockReturn = false;
    }, 3000))
  },
  // 开启心跳
  startWsHeartbeat({ state, commit, dispatch }) {
    console.log('心跳包', { state, commit, dispatch })
    state.timeoutObj && clearTimeout(state.timeoutObj)
    state.serverTimeoutObj && clearTimeout(state.serverTimeoutObj)
    commit('setTimeoutObj', setInterval(function() {
      // 判断websocket当前状态
      if (state.socket.readyState !== 1) {
        dispatch('reconnect')
      } else {
        const inuserCode = {
          type: 'heartBeat',
          data: {

          }
        }
        // const inmsg = { type: types, data: inuserCode }
        // 发送用户编码
        // this.socket.send(JSON.stringify(store.state.wsConnection.userCode));
        dispatch('sendMessage', inuserCode)
      }
    }, state.timeout))
  },

  // 重置websocket心跳
  resetHeartbeat({ state, commit, dispatch }) {
    clearTimeout(state.timeoutObj)
    clearTimeout(state.serverTimeoutObj)
    dispatch('startWsHeartbeat')
  },

  sendMessage({ state, commit, dispatch }, index) {
    const data = {
      type: index.type ?? 'userMessage',
      cilientType: '',
      clientCode: '',
      clientSerial: '',
      userCode: '',
      userToken: state.userToken,
      timeStamp: state.timeStamp,
      data: index.data ?? {},
      sign: ''
    }
    if (state.socket && state.socket.readyState === 1) {
      state.socket.send(
        JSON.stringify(data)
      )
    } else {
      dispatch('initWebSocket')
      state.socket.send(
        JSON.stringify(data)
      )
    }
  },
  close({ state, commit, dispatch }) {
    if (state.socket === null) {
      return
    }
    state.socket.close()
    commit('setSocket', null)
    commit('setUserToken', '')
    clearTimeout(state.timeoutObj)
    clearTimeout(state.serverTimeoutObj)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
